import { createRouter, createWebHashHistory, type RouteLocationNormalizedGeneric } from 'vue-router'
import { staticRoutes, rootRoutes, adminRoutes, userRoutes } from './routes'
import nprogress from 'nprogress'
import 'nprogress/nprogress.css'
import { SESSION } from '@/utils/storage'

nprogress.configure({ showSpinner: false })

const router = createRouter({
  history: createWebHashHistory(import.meta.env.VITE_ROUTER_BASE_URL),
  routes: [...staticRoutes, ...rootRoutes],
})

const setRoutes = (to: RouteLocationNormalizedGeneric) => {
  if (rootRoutes[0].children) return true
  if (SESSION.get('is_admin') === true) {
    rootRoutes[0].redirect = adminRoutes[0].path
    rootRoutes[0].children = adminRoutes
  } else {
    rootRoutes[0].redirect = userRoutes[0].path
    rootRoutes[0].children = userRoutes
  }
  router.addRoute(rootRoutes[0])
  return {
    path: to.path || '/',
    query: to.query || {},
    params: to.params || {},
    replace: true,
  }
}

export const resetRouter = () => {
  router.getRoutes().forEach((route) => {
    if (!route.meta.ignoreAuth && route.name) {
      router.removeRoute(route.name)
    }
  })
  delete rootRoutes[0].children
}

router.beforeEach((to) => {
  nprogress.start()
  const token = SESSION.get('access_token')
  if (token) {
    if (to.path === '/login') {
      return false
    }
    return setRoutes(to)
  } else {
    if (to.meta.ignoreAuth) {
      return true
    } else {
      return { path: '/login', replace: true }
    }
  }
})

router.afterEach(() => {
  nprogress.done()
})

export default router
